from page.ui_MainWindow import Ui_MainWindow
from PyQt5.QtWidgets import QMainWindow, QMessageBox
from call_page.call_arguments import Arguments
from call_page.call_control import Control


class MainWindow(QMainWindow, Ui_MainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.Argument_Page = Arguments()
        self.Control_Page = Control()
        self.stack.addWidget(self.Argument_Page)
        self.stack.addWidget(self.Control_Page)
        self.toolButton_control.clicked.connect(self.page_choose)
        self.toolButton_arguments.clicked.connect(self.page_choose)
        self.Argument_Page.pushButton_back.clicked.connect(self.page_choose)
        self.Control_Page.pushButton_back.clicked.connect(self.page_choose)
        self.Argument_Page.calibration_thread.Signal_p.connect(self.calibration)
        self.Argument_Page.calibration_thread.Signal_p1.connect(self.calibration1)
        self.Argument_Page.serial_connect.read_arduino.Signal_info.connect(self.info)
        self.mu = 1
        self.is_cam_opened = False
        self.Control_Page.pushButton_confirm.clicked.connect(self.pwm_pushButton)
        self.Control_Page.Signal_send.connect(self.send)

    def page_choose(self):
        sender = self.sender()
        if sender == self.toolButton_control:
            self.stack.setCurrentIndex(2)
        elif sender == self.toolButton_arguments:
            self.stack.setCurrentIndex(1)
            self.Argument_Page.com_list()
        else:
            self.stack.setCurrentIndex(0)

    def calibration(self, pwm):
        if self.Control_Page.is_camera_opened:
            self.Control_Page.pwm_send(pwm)
        else:
            QMessageBox.about(self, '摄像头未打卡', '请打开摄像头')

    def calibration1(self, count, k):
        self.read_cam_info(count, k)

    def pwm_pushButton(self):
        if self.Argument_Page.is_arduino_com_open:
            self.pwm_read_send()
        else:
            QMessageBox.about(self, 'Arduino串口未打开', '请打开串口')

    def pwm_read_send(self):
        p = float(self.Control_Page.lineEdit_pneumatic_cmd.text())
        self.Control_Page.pwm_send(p)

    def send(self, data):
        self.Argument_Page.serial_connect.arduino_send(data)

    def info(self, data):
        self.Control_Page.textBrowser_info.append(data)

    def read_cam_info(self, count, k):
        x = int(self.Control_Page.lineEdit_x.text())
        y = int(self.Control_Page.lineEdit_y.text())
        self.Argument_Page.calibration_thread.x[count][k] = x
        self.Argument_Page.calibration_thread.y[count][k] = y
